// 查找图书表
const { MongoClient, ServerApiVersion } = require('mongodb')
let dayjs = require('dayjs')
const { query } = require('express')

// 数据库地址
const uri = 'mongodb://localhost:27017/libraryDB'

// 连接数据库
const client = new MongoClient(uri, {
  serverApi: {
    version: ServerApiVersion.v1,
    strict: true,
    deprecationErrors: true,
  },
})

// 查看图书
const queryBooks = async (data) => {
  try {
    // 连接数据库
    await client.connect()
    // 获取数据库对象
    const db = client.db('libraryDB')

    // 获取图书表
    const booksDB = db.collection('books')
    // console.log(data)
    // 构造查询条件
    const condition = []
    Object.keys(query).forEach((key) => {
      // 如果值不为空，则构造模糊查询条件
      if (data[key]) {
        const regex = new RegExp(data[key])
      }
    })
    // 执行模糊查询
    // const regex = new RegExp()
    // console.log(data)
    const keyList = Object.keys(data)
    // console.log(keyList)
    if (keyList[0] === 'status') {
      // if (!Object.values(data).length) return
      // console.log(Object.values(data)[0])
      // const list = []
      // for (let index = 0; index < Object.values(data)[0].length; index++) {
      //   list.push({ status: item.flat(Infinity) })
      // }
      // data = list
      // console.log(list)
      const listType = []
      const list = data.status
      for (let i = 0; i < list.length; i++) {
        listType.push({ status: list[i] })
      }
      data = { $or: listType }
      console.log(listType)
    }
    const res = await booksDB.find(data).limit(100)
    // console.log(res, 11111)
    const list = []
    await res.forEach((element) => {
      list.push(element)
    })
    // const list = res.map((item) => item)
    return {
      msg: '查询成功',
      time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      msgCode: 10000,
      data: {
        total: list.length,
        list,
        success: true,
      },
    }
  } catch (error) {
    console.log(error)
    return {
      msg: '服务器异常',
      success: false,
      error,
    }
  }
}
module.exports = { queryBooks }
